// License Notification
//======================================================
// Copyright (c) 2010 Channel Intelligence Inc.
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// which accompanies this distribution, and is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// ======================================================




using System;
using System.Xml;
using System.IO;
using System.Reflection;
using System.Globalization;

namespace CIP4.Serializer
{
    public class GeneratorTemplateType : IDisposable
    {
        private TextWriter m_Writer;

        public TextWriter Writer
        {
            get { return m_Writer; }
        }
        private readonly XmlDocument _templatesDoc;
        public string this[string name]
        {
            get
            {
                if (_templatesDoc.DocumentElement == null)
                    throw new ApplicationException("Invalid template document");
                XmlNode nd = _templatesDoc.DocumentElement.SelectSingleNode("Template[@name='" + name + "']");
                if (nd != null)
                    return nd.InnerText.TrimStart(new[] { '\r', '\n' });

                throw new ArgumentException(String.Format("Unable to find a template called {0}", name));
            }
        }

        public GeneratorTemplateType(string template)
        {

            Assembly assem = typeof(GeneratorTemplateType).Assembly;
            Stream stream = assem.GetManifestResourceStream(string.Format("CIP4.Serializer.{0}.xml", template));
            _templatesDoc = new XmlDocument();
            if (stream == null)
                throw new ApplicationException("unexpected null stream - should be an assembly resource");
            _templatesDoc.Load(stream);
            m_Writer = new StringWriter(CultureInfo.CurrentCulture);
        }

        ~GeneratorTemplateType()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                m_Writer.Dispose();
            }
        }
    }
}
